// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    op,
    _id,
    _openid,
    status,
    pr
  } = event
  switch (op) {
    case 'checkImg':
      return checkImg(event.buffer);
      break;
    case 'apply':
      return apply();
      break;
    case 'review':
      return review();
      break;
    case 'getPrs':
      return getPrs();
      break;
    case 'getPrInfo':
      return getPrInfo();
      break;
  }
  async function checkImg(buffer) {
    try {
      const result = await cloud.openapi.security.imgSecCheck({
        media: {
          contentType: 'image/png',
          value: Buffer.from(buffer)
        }
      })
      if (result && result.errCode.toString() === '87014') {
        return {
          code: 500,
          msg: '内容含有违法违规内容',
          data: result
        }
      } else {
        return 'pass'
      }
    } catch (err) {
      // 错误处理
      if (err.errCode.toString() === '87014') {
        return {
          code: 500,
          msg: '内容含有违法违规内容',
          data: err
        }
      }
      return {
        code: 502,
        msg: '调用security接口异常',
        data: err
      }
    }
  }
  async function apply() {
    try {
      let data = pr
      data._openid = wxContext.OPENID
      data.createTime = db.serverDate()
      data.status = 0 //0-申请中，1-审核通过,2-审核拒绝
      let result = await db.collection('Promotion').add({
        data: data
      })
      return result
    } catch (err) {
      return err
    }
  }
  async function review() {
    let result = await db.collection('Promotion').doc(_id).update({
      data: {
        status: parseInt(status),
        review_id: wxContext.OPENID,
        review_time: db.serverDate()
      }
    })
    return result
  }
  async function getPrs() {
    const countResult = await db.collection('Promotion').where({
      status: parseInt(status),
      endDate:_.gte(db.serverDate())
    }).count()
    const total = countResult.total
    const $ = db.command.aggregate
    var d = new Date( Date.now()),
      a = $.dateFromString({
        dateString: d.toJSON()
      })
      let result = await db.collection('Promotion').aggregate()
      .addFields({         
          matched: $.gte(['$endDate', a]),  
         // status: parseInt(status)     
      }).match({      
          matched:true ,
          status: parseInt(status)     
      })
      .lookup({
        from: 'Merchant',
        localField: 'mch_id',
        foreignField: '_id',
        as: 'mch',
      })
      .end()
    // let result = await db.collection('Promotion')
    //   .aggregate()
    //   .addFields({
    //     matched: $.lte(['$endDate', a]),
    //   })
    //   .match({
    //     matched: !0
    //   })
    //   .end()
      // .match({
      //   status: parseInt(status)
      // })
      // .lookup({
      //   from: 'User',
      //   localField: '_openid',
      //   foreignField: '_openid',
      //   as: 'user',
      // })
      //.end()

    // let list = result.list
    // // for (let i = 0; i < list.length; i++) {
    // //   list[i].nickname = list[i].user[0].nickname
    // //   list[i].avatar = list[i].user[0].avatar
    // //   delete list[i].user
    // // }
    return {
      total: total,
      list: result.list
    }
  }
  async function getPrInfo() {
    let result = await db.collection('Promotion')
      .aggregate()
      .match({
        _id: _id
      })
      .lookup({
        from: 'Merchant',
        localField: 'mch_id',
        foreignField: '_id',
        as: 'mch',
      })
      .end()


    // .doc(_id).get()



    return result.list[0]
  }
}